package com.wy.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wy.entity.GoodsLogistics;
import com.wy.entity.GoodsOrder;
import com.wy.mapper.GoodsLogisticsMapper;
import com.wy.mapper.GoodsOrderMapper;
import com.wy.mapper.UserInfoMapper;
import com.wy.service.GoodsLogisticsService;
import com.wy.service.GoodsOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;

/**
 * @Author:王渝
 * @Date: 2022/11/30  11:17
 * @Version 1.0
 */
@Service
public class GoodsLogisticsServiceImpl extends ServiceImpl<GoodsLogisticsMapper, GoodsLogistics> implements GoodsLogisticsService {

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Autowired
    private GoodsOrderMapper goodsOrderMapper;

    @Autowired
    private GoodsLogisticsMapper goodsLogisticsMapper;

    @Transactional(rollbackFor = {})
    @Override
    public boolean receive(Long orderId) {
        LambdaUpdateWrapper<GoodsLogistics> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        lambdaUpdateWrapper.eq(GoodsLogistics::getOrderId,orderId);
        lambdaUpdateWrapper.set(GoodsLogistics::getStatus,"3");
        lambdaUpdateWrapper.set(GoodsLogistics::getReceivingTime, LocalDateTime.now());
        //更新状态为已收货和收货时间
        boolean update = this.update(lambdaUpdateWrapper);
        if(!update){
            return false;
        }
        //查询交易金额 卖家id
        GoodsOrder goodsOrder = goodsOrderMapper.selectById(orderId);
        BigDecimal transactionAmount = goodsOrder.getTransactionAmount();
        Long sellerUserId = goodsOrder.getSellerUserId();
        int i = userInfoMapper.addBalance(transactionAmount, sellerUserId);
        if(i == 0){
            //给商家钱
            throw new RuntimeException("确认收货失败");
        }
        return true;
    }

    @Override
    public void autoReceive() {
        List<Long> ids = goodsLogisticsMapper.getUnreceivedOrderIds();
        if(ids == null){
            return;
        }
        for (Long id : ids) {
            this.receive(id);
        }
    }
}
